package com.gjy.spring.b03;

import org.springframework.aop.framework.Advised;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.lang.reflect.Method;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-12-18 16:43:09
 */
@SpringBootApplication
public class B03 {

    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext context = SpringApplication.run(B03.class, args);

        Bean1 bean = context.getBean(Bean1.class);
        bean.setBean2(new Bean2());
        bean.init();

        showProxyAndTarget(bean);

        System.out.println("bean.getBean2() = " + bean.getBean2());
        System.out.println("bean.isInit() = " + bean.isInit());

        bean.m1();
        bean.m2();
        bean.m3();
        Method method = Bean1.class.getDeclaredMethod("m4");
        method.setAccessible(true);
        method.invoke(bean);

        context.close();
    }

    private static void showProxyAndTarget(Bean1 proxy) throws Exception {
        System.out.println("》》》》代理");
        System.out.println("proxy.init = " + proxy.init);
        System.out.println("proxy.bean2 = " + proxy.bean2);
        if (proxy instanceof Advised) {
            System.out.println("》》》》目标");
            Advised advised = (Advised) proxy;
            Bean1 target = (Bean1) advised.getTargetSource().getTarget();
            System.out.println(target);
            System.out.println("target.init = " + target.init);
            System.out.println("target.bean2 = " + target.bean2);
        }
    }
}
